//
//  YJNetworkManager.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/9.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit
import Alamofire

enum YJNetworkManagerError: Int {
    case repeatRefresh = -1
    case emptyAccessToken = -250
    
    // 枚举里面可以有属性
    var netDomain: String {
        get {
            return "cn.jim1024.error.net"
        }
    }
    
    var dbDomain: String {
        get {
            return "cn.jim1024.error.db"
        }
    }
    
    var errorDescription: String {
        get {
            switch self {
            case .repeatRefresh: return "重复刷新了！"
            case .emptyAccessToken: return "access_token 没有值"
            }
        }
    }
    
    // 枚举可以有方法
    func error() -> NSError {
        return NSError(domain: netDomain, code: self.rawValue, userInfo: ["errorDescription" : self.errorDescription])
    }
}

enum YJNetwotkManagerRequestType {
    case get
    case post
}

class YJNetworkManager: NSObject {
    
    class func request(type: YJNetwotkManagerRequestType = .get, urlStrig: String, parameters: [String : Any]? = nil, completion: @escaping ((_ result: AnyObject?, _ error: NSError?) -> ())) {
        let method = type == YJNetwotkManagerRequestType.post ? HTTPMethod.post : HTTPMethod.get
        
        var tempURLStr = urlStrig
        if !(urlStrig.hasPrefix("http://") || urlStrig.hasPrefix("https://") || urlStrig.hasPrefix("www.")) {
            tempURLStr = YJBaseURLStr + urlStrig
        }
        
        var params = parameters
        // 自己来拼接accessToken,外面不用传入accessToken
        guard let access_token = YJUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            JPrint("access_token 没有值")
            completion(nil, YJNetworkManagerError.emptyAccessToken.error())
            return
        }
        if params == nil {
            params = [String : Any]()
        }
        params!["access_token"] = access_token
        
        Alamofire.request(tempURLStr, method: method, parameters: params).responseJSON { (respons) in
            JPrint("currentURL: \(respons.request?.url)")
            guard let result = respons.result.value else {
                JPrint("请求失败: \(respons.result.error)")
                completion(nil, respons.result.error as NSError?)
                return
            }
            JPrint("请求成功: \(result)")
            completion(result as AnyObject?, nil)
        }
    }
}
